var path = require('path');
var fs = require('fs');
var write = require('./backend/write');

var argvs = process.argv;
if (argvs.length >= 3) {
    var moduleName = argvs[2];
    var fileName = argvs[3] || moduleName;
    
    fs.stat(path.resolve(moduleName, `${fileName}.js`), function(err, stat) {
        if (err) {
            write(path.resolve(moduleName, `${fileName}.js`))
                .write(`(function (root, factory) {\n  typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n  root.${fileName} = factory();\n}(this, function () { 'use strict';\n\n  var ${fileName} = function() {}\n  return ${fileName}\n\n}))\n`);
            
            var testName = `${fileName}Test`;
            fs.stat(path.resolve(moduleName, `${testName}.js`), function(err, stat) {
                if (err) {
                    write(path.resolve(moduleName, `${testName}.js`))
                        .write(`var demo = require("./${fileName}");\nconsole.log(demo());`);
                } else {
                    console.log(`The module ${moduleName}/${testName}.js has been exist.`);
                }
            });
        } else {
            console.log(`The module ${moduleName}/${fileName}.js has been exist.`);
        }
    });

} else {
    console.log("Usage: " + path.basename(argvs[0]) + " " + path.basename(argvs[1]) + " {module name} [file name]");
}